let router = require('express').Router()
let db = require('../db')
let utils = require('../utils')

// 处理查询条件
let queryHandler = (query = {}, keys = []) => {
    let where = ''
    Object.keys(query).forEach(k => {
        if (keys.includes(k) && query[k]) {
            where += k + '=' + query[k] + '&&'
        }
    })
    where = where ? ' where ' + where.slice(0, -2) : ''
    return where
}

// 处理分页条件
let limitHandler = query => {
    let { pageSize = 10, pageNum = 1 } = query
    let limit = ' limit ' + (pageNum - 1) * pageSize + ',' + pageSize
    return limit
}

// 列表
router.get('/info', async (req, res, next) => {
    let where = queryHandler(req.query, ['cate_id', 'author_id'])
    let limit = limitHandler(req.query)
    let data = await db({
        sql: 'select id,title,content,cover_img,pub_date,state,cate_id,author_id from en_article_info' + where + limit,
        next
    })
    let total = await db({
        sql: 'select count(id) as total from en_article_info' + where,
        next
    })
    res.success('', {
        rows: data,
        total: total[0].total
    })
})

// 新增
router.post('/info', async (req, res, next) => {
    req.body.author_id = req.auth.id
    req.body.pub_date = utils.parseTime(new Date())
    await db({
        sql: 'insert into en_article_info set ?',
        value: req.body,
        next
    })
    res.success('操作成功！')
})

// 编辑
router.put('/info', async (req, res, next) => {
    await db({
        sql: 'update en_article_info set ? where id = ?',
        value: [req.body, req.body.id]
    })
    res.success('操作成功！')
})

// 删除
router.delete('/info/:id', async (req, res, next) => {
    await db({
        sql: 'delete from en_article_info where id = ?',
        value: req.params.id
    })
    res.success('操作成功！')
})

// 按天查文章数量
router.get('/info_group_pub_date', async (req, res, next) => {
    let data = await db({
        sql: 'select pub_date from en_article_info'
    })
    let result = data.reduce((result, curr) => {
        let date = curr.pub_date.split(' ')[0]
        result[date] ? result[date]++ : result[date] = 1
        return result
    }, {})
    let { date } = req.query
    date && (result = result[date] || 0)
    res.success('', result)
})

// 总量
router.get('/info/count', async (req, res, next) => {
    let data = await db({
        sql: 'select count(id) as count from en_article_info',
        next
    })
    res.success('', data[0])
})

module.exports = router